﻿using DotNetCommon.Data;
using DotNetCommon.Logger;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace DotNetCommon.Web.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class ExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this.logger = logger;
        }

        /// <summary>
        /// override
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            var logMsg = $"全局异常: {context.Exception?.Message}{Environment.NewLine}{context.Exception?.StackTrace}";
            if (context?.Exception?.InnerException != null)
            {
                logMsg = $@"全局异常: {context.Exception.Message}
inner exception: {context.Exception.InnerException.Message}
stacktrace: {context.Exception.StackTrace}
inner stacktrace: {context.Exception.InnerException.StackTrace}";
            }
            logger.LogError(logMsg);
            var msg = context.Exception.Message;
            var result = Result.NotOk(msg);
            context.Result = new JsonResult(result);
            return;
        }

        /// <summary>
        /// override
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }
    }
}
